package com.zang.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 二叉树的前序遍历
 *
 * @author ZVerify
 * @since 2022/10/22 10:15
 * @see <a href="https://leetcode.cn/problems/binary-tree-preorder-traversal/">...</a>
 **/
public class 二叉树的前序遍历 {

    // 递归法
    List<Integer> list = new ArrayList<>();

    public List<Integer> preorderTraversal(TreeNode root) {

        dfs(root);
        return list;
    }
    void dfs(TreeNode root){
        if (root==null) return;
        list.add(root.val);
        dfs(root.left);
        dfs(root.right);
    }

    // 迭代法
    public List<Integer> iteration(TreeNode root) {

        Stack<TreeNode> treeNodes = new Stack<>();
        List<Integer> arrayList = new ArrayList<>();
        if (root==null) return arrayList;

        treeNodes.push(root);

        while (!treeNodes.empty()) {
            TreeNode pop = treeNodes.pop();
            arrayList.add(pop.val);
            if (pop.right!=null) treeNodes.push(pop.right);
            if (pop.left!=null) treeNodes.push(pop.left);
        }
        return arrayList;
    }

}
